<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Log;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $password = $this->request->post('password');
        if(!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/',$password)){
            $this->error('密码必须6-12位数字和字母组合');
        }
        $email = $this->request->post('email','');
        $mobile = $this->request->post('mobile');
        $username = $this->request->post('username',preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $mobile));
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('账号密码必传!'));
        }
//        if ($email && !Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式不正确!'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('验证码错误!'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $log = new Log();
            $log->addLogMessge($data['userinfo']['id'],'恭喜您注册成功');
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改用户信息
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editUserinfo(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $data['username'] = input('param.username');
            $data['nickname'] = input('param.nickname');
            $data['email'] = input('param.email');
            $data['mobile'] = input('param.mobile');
            $data['gender'] = input('param.gender');
            $data['avatar'] = input('param.avatar');

            $result = db('user')->where('id',$user->id)->update($data);
            if($result){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(){

        $this->success('',$this->auth->getUser());
    }

    /***
     * 验证token是否过期
     */
    public function checkToken(){
        $user = $this->auth->getUser();
        if($user->token_time < time()){
            $this->error('token已过期',null,-101);
        }

        $this->success('');
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type",'mobile');
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email",'');
        $newpassword = $this->request->post("newpassword");
        if(!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/',$newpassword)){
            $this->error('密码必须6-12位数字和字母组合');
        }

        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('未知错误!'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号格式不正确'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__( '用户还未注册!'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('验证码错误!'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 根据旧密码设置新密码
     */
    public function oldResetpwd(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $oldpassword = $this->request->post("oldpassword");
            if(!$oldpassword){
                $this->error('旧密码不能为空');
            }

            if($this->auth->getEncryptPassword($oldpassword,$user->salt) != $user->password){
                $this->error('原密码错误');
            }

            $newpassword = $this->request->post("newpassword");
            if(!$newpassword){
                $this->error('新密码不能为空');
            }

            if(!preg_match('/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/',$newpassword)){
                $this->error('密码必须6-12位数字和字母组合');
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword, true);
            if ($ret) {
                $this->success(__('Reset password successful'));
            } else {
                $this->error($this->auth->getError());
            }
        }
    }


    /**
     * 新增收货地址
     */
    public function addAddress(){
        if(request()->isPost()){
            $user = $this->auth->getUser();

            $province = $this->getAreaid(input('param.province_code'));
            $city = $this->getAreaid(input('param.city_code'));
            $region = $this->getAreaid(input('param.region_code'));

            $data['user_id'] = $user->id;
            $data['name'] = input('param.name');
            $data['phone'] = input('param.phone');
            $data['province_code'] = input('param.province_code');
            $data['city_code'] = input('param.city_code');
            $data['region_code'] = input('param.region_code');
            $data['province_id'] = $province['id'];
            $data['city_id'] = $city['id'];
            $data['region_id'] = $region['id'];
            $data['province_name'] = $province['name'];
            $data['city_name'] = $city['name'];
            $data['region_name'] = $region['name'];
            $data['detail'] = input('param.detail');
            $data['isdefault'] = input('param.isdefault');
            $data['createtime'] = time();
            $data['email'] = input('param.email');

            if(!$data['name'] || !$data['phone'] || !$data['detail']){
                $this->error('收货人姓名,收货人电话,详细地址必填');
            }

            $isdefault_id = db('address')->where('user_id',$data['user_id'])->where('isdefault',1)->value('address_id');
            db('address')->where('user_id',$data['user_id'])->where('address_id',$isdefault_id)->update(['isdefault'=>0]);
            $return = db('address')->insert($data);
            if($return){
                $this->success('添加成功');
            }else{
                $this->error('添加失败');
            }
        }
    }

    /**
     *修改收货地址
     */
    public function editAddress(){
        $user = $this->auth->getUser();

        $province = $this->getAreaid(input('param.province_code'));
        $city = $this->getAreaid(input('param.city_code'));
        $region = $this->getAreaid(input('param.region_code'));

        $data['user_id'] = $user->id;
        $data['address_id'] = input('param.address_id');
        $data['name'] = input('param.name');
        $data['phone'] = input('param.phone');
        $data['province_code'] = input('param.province_code');
        $data['city_code'] = input('param.city_code');
        $data['region_code'] = input('param.region_code');
        $data['province_id'] = $province['id'];
        $data['city_id'] = $city['id'];
        $data['region_id'] = $region['id'];
        $data['province_name'] = $province['name'];
        $data['city_name'] = $city['name'];
        $data['region_name'] = $region['name'];
        $data['detail'] = input('param.detail');
        $data['isdefault'] = input('param.isdefault');
        $data['updatetime'] = time();
        $data['email'] = input('param.email');

        if(!$data['name'] || !$data['phone'] || !$data['detail']){
            $this->error('收货人姓名,收货人电话,详细地址必填');
        }

        $isdefault_id = db('address')->where('user_id',$data['user_id'])->where('isdefault',1)->value('address_id');
        if($isdefault_id != $data['address_id']){
            db('address')->where('user_id',$data['user_id'])->where('address_id',$isdefault_id)->update(['isdefault'=>0]);
        }

        $return = db('address')->where('user_id',$data['user_id'])->where('address_id',$data['address_id'])->update($data);
        if($return){
            $this->success('编辑成功');
        }else{
            $this->error('编辑失败');
        }
    }

    /**
     * 设置默认地址
     */
    public function setDefaultAddress(){
        if(request()->isPost()){
            $user = $this->auth->getUser();

            $data['user_id'] = $user->id;
            $data['isdefault'] = input('param.isdefault');
            $data['address_id'] = input('param.address_id');

            $isdefault_id = db('address')->where('user_id',$data['user_id'])->where('isdefault',1)->value('address_id');
            if($isdefault_id != $data['address_id']){
                db('address')->where('user_id',$data['user_id'])->where('address_id',$isdefault_id)->update(['isdefault'=>0]);
            }

            $return = db('address')->where('user_id',$data['user_id'])->where('address_id',$data['address_id'])->update($data);
            if($return){
                $this->success('设置成功');
            }else{
                $this->error('设置失败');
            }
        }
    }

    /**
     * 用户地址列表
     */
    public function listAddress(){
        $user = $this->auth->getUser();

        $data['user_id'] = $user->id;
        $list = db('address')->where('user_id',$data['user_id'])->select();

        $this->success('',$list);
    }


    /**
     * 用户地址详情
     */
    public function detailAddress(){
        $user = $this->auth->getUser();

        $data['user_id'] = $user->id;
        $data['id'] = input('param.id');
        $info = db('address')->where('user_id',$data['user_id'])->where('address_id',$data['id'])->find();

        $this->success('',$info);
    }


    /**
     * 删除地址
     */
    public function delAddress(){
        $user = $this->auth->getUser();

        $data['user_id'] = $user->id;
        $data['id'] = input('param.id');
        $info = db('address')->where('user_id',$data['user_id'])->where('address_id',$data['id'])->delete();
        if($info){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    //根据code获取id
    protected function getAreaid($code = ''){
        if(!$code){
            $this->error('code必传');
        }

        $info = db('area')->where('areacode',$code)->find();

        return $info;
    }

    /***
     * 意见反馈
     */
    public function addOpinion(){
        if(request()->isPost()){
            $user = $this->auth->getUser();

            $data['user_id'] = $user->id;
            $data['type'] = input('param.type');
            $data['name'] = input('param.name');
            $data['img'] = input('param.img');
            $data['createtime'] = time();

            $result = db('opinion')->insert($data);
            if($result){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }
    }

    /**
     * 添加支付宝账号
     */
    public function aliName(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $data['ali_name'] = input('param.ali_name');
            $data['ali_username'] = input('param.ali_username');

            $result = db('user')->where('id',$user->id)->update($data);
            if($result){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }
    }

    /**
     * 添加银行账号
     */
    public function aliBankName(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $data['bank_name'] = input('param.bank_name');
            $data['bank_username'] = input('param.bank_username');

            $result = db('user')->where('id',$user->id)->update($data);
            if($result){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }
    }

    /***
     * 申请提现
     */
    public function withdrawMoney(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $data['money'] = input('param.money');
            if($user->money < $data['money']){
                $this->error('超出可提现金额');
            }

            if($data['money'] <= 0){
                $this->error('提现金额不合法');
            }

            $data['type'] = input('param.type');
            if($data['type'] == 1){
                $data['name'] = $user->ali_name;
                $data['username'] = $user->ali_username;
            }else{
                $data['name'] = $user->bank_name;
                $data['username'] = $user->bank_username;
            }
            $data['user_id'] = $user->id;
            $data['createtime'] = time();
            $result = db('withdraw_money')->insert($data);
            $user_result = db('user')->where('id',$user->id)->setDec('money',$data['money']);
            if($result && $user_result){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }
    }

    /**
     * 我的提现列表
     */
    public function withdrawMoneyList(){
        $user = $this->auth->getUser();

        $page = input('param.page',1);
        $limit = input('param.limit',10);

        $list = db('withdraw_money')->where('user_id',$user->id)->order('id desc')->paginate($limit,false,['page'=>$page]);
        $data = tp_builde_page($list);
        foreach ($data['data'] as $key => $value){
            $data['data'][$key]['createtime_text'] = date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success('',$data);
    }

    /**
     * 站内消息表
     */
    public function stationInformation(){
        $user = $this->auth->getUser();

        $page = input('param.page',1);
        $limit = input('param.limit',10);

        $where = [];
        if(input('param.createtime')){
            $createtime = explode(',', input('param.createtime'));
            $where['createtime'] = ['BETWEEN', [strtotime($createtime[0]), strtotime($createtime[1])]];
        }

        input('param.type') && $where['type'] = input('param.type');

        $list = db('station_information')->where('user_id',$user->id)->where($where)->order('id desc')->paginate($limit,false,['page'=>$page]);
        $data = tp_builde_page($list);
        foreach ($data['data'] as $key => $value){
            $data['data'][$key]['createtime_text'] = date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success('',$data);
    }

    /**
     * 批量设置已读
     */
    public function setStationInformation(){
        $user = $this->auth->getUser();
        $ids = explode(',',input('param.ids'));
        if(count($ids) <= 0){
            $this->error('请选择消息');
        }

        foreach ($ids as $key => $value){
            $data['type'] = 1;

            $result = db('station_information')->where('user_id',$user->id)->where('id',$value)->update($data);
        }

        $this->success('成功');
    }

    /**
     * 消息删除
     */
    public function delStationInformation(){
        $user = $this->auth->getUser();
        $ids = explode(',',input('param.ids'));

        foreach ($ids as $key => $value){
            $result = db('station_information')->where('user_id',$user->id)->where('id',$value)->delete();
        }

        if($result){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }

    /**
     * 确认收货
     */
    public function confirmReceipt(){
        if(request()->isPost()){
            $user = $this->auth->getUser();
            $order_code = input('param.order_code');

            if(!$order_code){
                $this->error('订单号必传');
            }

            Db::startTrans();
            $info = db('demand_order')->where('user_id',$user->id)->where('order_code',$order_code)->find();

            if($info['pay_status'] != 1 && $info['status'] != 'normal'){
                Db::rollback();
                $this->error('该订单不可确认收货');
            }

            $result = db('demand_order')->where('id',$info['id'])->where('order_code',$order_code)->update(['status' => 'confirm_receipt']);
            if($result){
                db('user')->where('id',$info['demand_user_id'])->setInc('money',$info['money']);
                Db::commit();
                $this->success('成功');
            }else{
                Db::rollback();
                $this->error('失败');
            }
        }
    }

}
